package mas;

import java.util.concurrent.LinkedBlockingQueue;

/** Class provides the ability to queue and enqueue data in a first in first out 
 * fashion
 * 
 * Advanced Java Programming - ICA 2 Middleware 
 * @author Carl Morphet, Matt Constable, Stephen Pammenter
 * Teesside University
 * Created: Apr 11, 2012
 * @version %I% 
 */
public class BlockingQueue
{
    /** A linked blocking queue which acts as the MetaAgents message queue */
    private LinkedBlockingQueue itemsToQueue = new LinkedBlockingQueue();
    
    /** The terminating string, which when passed in a Message object will stop 
     * further queuing */
    private static final String SHUTDOWN_REQ = "SHUTDOWN";

    /** Method which adds the Message object onto the queue unless the 
     * termination variable has been set to true
     * 
     * @param m The message to be enqueued
     */
    public void enqueue(Message m)
    {
        if(m.getID().equals(SHUTDOWN_REQ)) 
            return;
        try
        {
            itemsToQueue.put((Message) m);  
        }
        catch (InterruptedException iex)
        {
            System.out.println("Blocking queue enqueue error: " + iex.getMessage());
        }
    }
    
    /** Method which removes and returns the message object at the top of the 
     * queue
     * 
     * @return The message object at the top of the queue
     */
    public Message dequeue()
    {
        Message m = null;
        try
        {
            m = (Message) itemsToQueue.take();
        }
        catch(InterruptedException iex)
        {
            System.err.println("Blocking queue dequeue error: " + iex.getMessage());
        }
        finally
        {
            return m;
        }
    }
}